package org.dht.com.msg;

import java.util.HashMap;
import java.util.Map.Entry;

import javax.xml.bind.annotation.adapters.XmlAdapter;

/**
 * The <code>XmlAdapterDatasMap</code> class implement mapped from
 * <code>HashMap<String, byte[]></code> to <code>Params</code> and vice versa
 *  
 */
public final class XmlAdapterDatasMap extends
		XmlAdapter<Datas, HashMap<String, byte[]>> {
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.xml.bind.annotation.adapters.XmlAdapter#unmarshal(java.lang.Object)
	 */
	public HashMap<String, byte[]> unmarshal(Datas datas) throws Exception {

		HashMap<String, byte[]> hashMap = new HashMap<String, byte[]>();

		for (Data data : datas.getData()) {
			hashMap.put(data.getName(), data.getBytes());
		}

		return hashMap;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.xml.bind.annotation.adapters.XmlAdapter#marshal(java.lang.Object)
	 */
	public Datas marshal(HashMap<String, byte[]> hashMap) throws Exception {
		Datas datas = new Datas();

		for (Entry<String, byte[]> entry : hashMap.entrySet()) {
			Data data = new Data();
			data.setName(entry.getKey());

			if (entry.getValue() == null) {
				data.setBytes(new byte[] {});
			} else {
				data.setBytes(entry.getValue());
			}

			datas.getData().add(data);
		}

		return datas;
	}

}
